const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

// 判断后台返回时间与当前时间间隔多少
const dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function (milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function (dateStr) {
		var date = this.parse(dateStr)
    var diff = Date.now() - date.getTime();
		// 当前日期下的多少天时间差
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		// 当前日期下的多少月时间差
		if (diff < this.UNITS['月']) {
			return this.humanize(diff);
		}
		// 当前日期下的多少年时间差
		if (diff < this.UNITS['年']) {
			return this.humanize(diff);
		}
    // 如果不是当前日期下返回月-日
    const oldDate = (dateStr.split(' ')[0]).slice(5)
    return oldDate
  },
  // 将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
	parse: function (str) {
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
};

// 2个日期天数差
function getDays(strDateStart, strDateEnd){
	let strSeparator = "-"; //日期分隔符
	let oDate1;
	let oDate2;
	let iDays;
	oDate1= strDateStart.split(strSeparator);
	oDate2= strDateEnd.split(strSeparator);
	let strDateS = new Date(oDate1[0], oDate1[1]-1, oDate1[2]);
	let strDateE = new Date(oDate2[0], oDate2[1]-1, oDate2[2]);
	//把相差的毫秒数转换为天数
	iDays = parseInt(Math.abs(strDateS - strDateE ) / 1000 / 60 / 60 /24)
	return iDays ;
}

// 表情转码
function utf16toEntities(str) {
	// 检测utf16字符正则
	let patt = /[\ud800-\udbff][\udc00-\udfff]/g;
	str = str.replace(patt, function(char) {
		let H, L , code;
		if(char.length === 2) {
			// 取出高位
			H = char.charCodeAt(0);
			// 取出低位
			L = char.charCodeAt(1);
			// 转换算法
			code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00;
			return '&#' + code + ';'
		} else {
			return char;
		}
	});
	return str;
}

// 表情解码
function uncodUtf16(str) {
	let reg = /\&#.*?;/g;
	let result = str.replace(reg, function (char) {
		let H, L, code;
		if(char.length === 9) {
			code = parseInt(char.match(/[0-9]+/g));
			H = Math.floor((code - 0x10000) / 0x400) + 0xD800;
			L = (code - 0x10000) % 0x400 + 0xDC00;
			return unescape('%u' + H.toString(16) + '%u' + L.toString(16));
		} else {
			return char;
		}
	});
	return result
}

module.exports = {
	getDays: getDays,
  dateUtils: dateUtils,
	formatTime: formatTime,
	uncodUtf16: uncodUtf16,
	utf16toEntities: utf16toEntities
}
